import { VideoState } from '@renderer/enums/settingEnum'
import { useSettingsStore } from '@renderer/store/modules/settings.store'
import { VideoType } from '@renderer/types/store'
import useConvert from './useConvert'

const useVideo = () => {
  const { ipc } = window

  const { isRun } = useConvert()

  // 获取 settingsStore
  const settingsStore = useSettingsStore()

  // 格式化文件大小
  const formatFileSize = (bytes: number): string => {
    if (bytes === 0) return '0 B'
    const k = 1024
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
    const i = Math.floor(Math.log(bytes) / Math.log(k))
    return (bytes / Math.pow(k, i)).toFixed(2) + ' ' + sizes[i]
  }

  const removeFile = async (file: VideoType) => {
    if (file.state === VideoState.CONVERTING) {
      // 提示用户正在转换中是否确定删除
      if (confirm('文件正在转换中，确定要删除吗？')) {
        await ipc.video.cancelConvert(file.path)
      } else {
        return // 用户取消删除操作
      }
    }

    // 删除文件
    settingsStore.removeFile(file.path)

    // 检查是否还有任务
    if (settingsStore.files.length === 0) {
      isRun.value = false // 如果没有任务，更新 isRun 状态
    }
  }

  return {
    removeFile,
    formatFileSize
  }
}

export default useVideo
